﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLBH.DTO;
using Module.Category.Properties;
using QLBH.Base;
using QLBH.Model.Controller;
using System.Security.Cryptography;
using QLBH.DataModel;
using System.Transactions;

namespace Module.Category
{
    public partial class StaffInfoDialog : Form
    {
        private eDialogType dialogType;

        public eDialogType DialogType
        {
            get { return dialogType; }
            set 
            { 
                dialogType = value;
                if (dialogType == eDialogType.DL_ADD)
                {
                    this.Text = "Thêm nhân viên";
                    this.Icon = Icon.FromHandle(Resources.add_24.GetHicon());
                }
                else
                {
                    this.Text = "Sửa thông tin nhân viên";
                    this.Icon = Icon.FromHandle(Resources.write_24.GetHicon());
                }
            }
        }
        private NhanVienDTO staff;

        public NhanVienDTO Staff
        {
            get { return staff; }
            set 
            { 
                staff = value;
                
            }
        }

        public StaffInfoDialog()
        {
            InitializeComponent();
            staff = new NhanVienDTO();

            

        }

        private void labelX5_Click(object sender, EventArgs e)
        {

        }

        private void labelAddPosition_Click(object sender, EventArgs e)
        {
            PositionDialog addPositionDlg=new PositionDialog();
            addPositionDlg.DialogType = eDialogType.DL_ADD;
            if (addPositionDlg.ShowDialog()==DialogResult.OK)
            {
                LoadPositions();
                cmbPosision.SelectedValue = addPositionDlg.Position.Id;
            }
        }
        private void LoadPositions()
        {
            List<ChucVuDTO> positions = PositionController.Instance.GetAll().ToDTOs().ToList();
            cmbPosision.DataSource = positions;
            cmbPosision.DisplayMember = "TenCV";
            cmbPosision.ValueMember = "Id";
                        
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (IsValidValue())
            {
                try
                {
                    UpdateInformationfromControl();
                    if (dialogType == eDialogType.DL_ADD)
                    {
                        AddNewStaff();
                    }
                    else
                    {
                        UpdateStaff();
                    }
                    DialogResult = DialogResult.OK;
                    this.Close();
                }
                catch (AccountException aex)
                {
                    MessageBox.Show(aex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUserName.SelectAll();
                    txtUserName.Focus();
                }
                catch (ExmailException eex)
                {
                    MessageBox.Show(eex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmail.SelectAll();
                    txtEmail.Focus();
                }
                catch (PhoneNumberException pex)
                {
                    MessageBox.Show(pex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPhoneNumber.SelectAll();
                    txtPhoneNumber.Focus();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }                              
        }

        private void UpdateStaff()
        {
            using (TransactionScope scope = new TransactionScope())
            {

                NhanVien newStaff = StaffController.Instance.Edit(staff.ToEntity());

                //Add account
                Account account = AccountController.Instance.FindBy(ac => ac.NhanVienId == newStaff.Id).FirstOrDefault();
                account.UserName = txtUserName.Text;
                account.Password = null;
                
                AccountController.Instance.Edit(account);

                scope.Complete();
            }  
        }

        private void AddNewStaff()
        {

            using (TransactionScope scope = new TransactionScope())
            {

                NhanVien newStaff = StaffController.Instance.Add(staff.ToEntity());

                //Add account
                AccountDTO account = new AccountDTO();
                account.UserName = txtUserName.Text;
                account.Password = null;
                account.NhanVienId = newStaff.Id;

                AccountController.Instance.Add(account.ToEntity());

                scope.Complete();
            }           
        }
        /// <summary>
        /// Update information from control to object
        /// </summary>
        private void UpdateInformationfromControl()
        {
            staff.DienChi = txtAddress.Text;
            staff.Email = txtEmail.Text;
            staff.MucLuong = long.Parse(txtSafery.Text);
            staff.SDT = txtPhoneNumber.Text;
            staff.TenNV = txtFullname.Text;
            staff.ChucVuId = (int)cmbPosision.SelectedValue;
            staff.PhongBanId = (int)cmbDepartment.SelectedValue;
            staff.STK = txtBankNumber.Text;
            staff.NganHang = txtBankName.Text;
            staff.ChiNhanh = txtBankdiv.Text;
        }
        /// <summary>
        /// Check valid value
        /// </summary>
        /// <returns></returns>
        private bool IsValidValue()
        {
            //User Name
            try
            {
                DataInputHelper.CheckTextData(txtUserName.Text, "Tên đăng nhập");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUserName.SelectAll();
                txtUserName.Focus();
                return false;
            }
            //Full Name
            try
            {
                DataInputHelper.CheckTextData(txtFullname.Text, "Họ tên");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtFullname.SelectAll();
                txtFullname.Focus();
                return false;
            }
            //Full Name
            try
            {
                DataInputHelper.CheckIntValue(txtSafery.Text, "Mức lương");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtSafery.SelectAll();
                txtSafery.Focus();
                return false;
            }
            //Position
            if (cmbPosision.SelectedItem == null)
            {
                MessageBox.Show("Bạn chưa chọn chức vụ", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbPosision.Focus();
            }
            //Dept
            if (cmbDepartment.SelectedItem==null)
            {
                MessageBox.Show("Ban chưa chọn phòng", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbDepartment.Focus();
            }
            if (txtPhoneNumber.Text!="")
            {
                try
                {
                    DataInputHelper.CheckPhoneNumber(txtPhoneNumber.Text);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPhoneNumber.SelectAll();
                    txtPhoneNumber.Focus();
                    return false;
                }
            }
            if(txtEmail.Text!="")
            {
                try
                {
                    DataInputHelper.CheckEmailData(txtEmail.Text);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmail.SelectAll();
                    txtEmail.Focus();
                    return false;
                }
            }
            return true;            
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void StaffInfoDialog_Load(object sender, EventArgs e)
        {
            LoadPositions();
            LoadDepartments();

            if (dialogType == eDialogType.DL_EDIT)
            {
                txtFullname.Text = staff.TenNV;
                txtAddress.Text = staff.DienChi;
                txtBankdiv.Text = staff.ChiNhanh;
                txtBankName.Text = staff.NganHang;
                txtBankNumber.Text = staff.STK;
                txtEmail.Text = staff.Email;
                txtPhoneNumber.Text = staff.SDT;
                txtSafery.Text = staff.MucLuong.ToString();

                Account currentAccount = AccountController.Instance.FindBy(ac => ac.NhanVienId == staff.Id).FirstOrDefault();
                txtUserName.Text = currentAccount.UserName;

                cmbDepartment.SelectedValue = staff.PhongBanId;
                cmbPosision.SelectedValue = staff.ChucVuId;
            }
        }

        private void LoadDepartments()
        {
            List<PhongBanDTO> departments = DeptController.Instance.GetAll().ToDTOs().ToList();
            cmbDepartment.DataSource = departments;
            cmbDepartment.DisplayMember = "TenPhong";
            cmbDepartment.ValueMember = "Id";
        }

        private void labelDepartment_Click(object sender, EventArgs e)
        {
            AddEditDeptDlg addDept = new AddEditDeptDlg();
            addDept.DialogType = eDialogType.DL_ADD;
            if (addDept.ShowDialog() == DialogResult.OK)
            {
                LoadDepartments();
                cmbDepartment.SelectedValue = addDept.NewDept.Id;
            }
        }
    }
}
